# -*- coding:utf-8 -*-

from rest_framework import serializers
from basic.models import ElevatorInfo, ElevatorPersonInfo, ElevatorStatistics, ElevatorFittings
from users.models import AuthUser, Person, Registry
from manufacturer.models import AlarmMsg, AuthorityCode
import random
import json
import datetime


class ElevatorSerializer(serializers.ModelSerializer):

    class Meta:
        model = ElevatorInfo
        fields = ("id", "elevator_name", "elevator_no", "internal_no", "register_code", "factory_no", "elevator_model",
                  "installation_company", "maintain_company", "property_company", "rated_load", "elevator_type",
                  "usage_status", "stations", "rated_speed", "product_company", "elevator_property", "inspection_company",
                  "maintain_company_name", "property_company_name", "update_by", "service_id", "qr_code",
                  "elevator_cycle", "num", "address", "manufacturer_company", "manufacturer_company_name",
                  "next_yearly_inspection_date", "phone_num", "inspection_conclusion", "inspection_people")


class ElevatorListSerializer(serializers.ModelSerializer):
    update_by_people = serializers.SerializerMethodField()
    # usage_status = serializers.CharField(source='get_usage_status_display')
    # worker = serializers.SerializerMethodField()
    # elevator_worker = serializers.SerializerMethodField()
    elevator = serializers.SerializerMethodField()
    # record = serializers.SerializerMethodField()
    maintain_company_name = serializers.SerializerMethodField()
    property_company_name = serializers.SerializerMethodField()
    telephone = serializers.SerializerMethodField()
    # elevator_type_choice = serializers.SerializerMethodField()
    is_online = serializers.SerializerMethodField()
    usage_status = serializers.SerializerMethodField()
    follow = serializers.SerializerMethodField()

    class Meta:
        model = ElevatorInfo
        fields = ("id", "elevator_name", "elevator_no", "internal_no", "register_code", "property_company",
                  "factory_no", "elevator_model", "installation_company", "maintain_company_name", "maintain_company",
                  "property_company_name", "product_company", "elevator_property", 'update_by_people', 'update_time',
                  "usage_status", "qr_code", "rated_load", "rated_speed", "stations", "elevator_type", "contract",
                  "elevator", "registry_status", "telephone", "elevator_cycle", "create_time", "is_online", "num",
                  "address", "manufacturer_company_name", "manufacturer_company", "next_yearly_inspection_date",
                  "phone_num", "next_time", "follow", "inspection_company")

    def get_follow(self, obj):
        user = self.context['request'].user.id
        return 1 if user in obj.follows() else 0

    def get_maintain_company_name(self, obj):
        maintain_company_name = obj.maintain_company.name if obj.maintain_company else ""
        return maintain_company_name

    def get_property_company_name(self, obj):
        property_company_name = obj.property_company.name
        return property_company_name

    def get_is_online(self, obj):
        ac = AuthorityCode.objects.filter_active(elevator_code=obj.register_code).first()
        if ac and ac.is_online:
            return 1
        return 0

    def get_usage_status(self, obj):
        return obj.get_usage_status_display()


    # def get_elevator_type_choice(self, obj):
    #     elevator_type = obj.elevator_type
    #     elevator_type_choice = {}
    #     if elevator_type == 10:
    #         elevator_type_choice['elevator_type_item'] = u'国标-曳引电梯-半月'
    #         elevator_type_choice['maintain_type'] = 190
    #     elif elevator_type == 20:
    #         elevator_type_choice['elevator_type_item'] = u'国标-液压电梯-半月'
    #         elevator_type_choice['maintain_type'] = 110
    #     elif elevator_type == 30:
    #         elevator_type_choice['elevator_type_item'] = u'国标-杂物电梯-半月'
    #         elevator_type_choice['maintain_type'] = 150
    #     elif elevator_type == 40:
    #         elevator_type_choice['elevator_type_item'] = {}
    #     return elevator_type_choice

    # def get_worker(self, obj):
    #     worker = []
    #     elevator_id = obj.id
    #     for worker_type in [10, 20, 30]:
    #         worker_info = dict()
    #         worker_info["worker_type"] = worker_type
    #         worker_info["worker_person"] = []
    #         maintain_workers_qs = ElevatorPersonInfo.objects.filter(elevator=elevator_id, worker_type=worker_type)
    #         for item in maintain_workers_qs:
    #             worker_item = dict()
    #             worker_item['worker_id'] = item.worker.id
    #             worker_item['worker_name'] = item.worker.auth_user.real_name
    #             worker_info["worker_person"].append(worker_item)
    #         worker.append(worker_info)
    #     return worker

    # def get_elevator_worker(self, obj):
    #     elevator_id = obj.id
    #     qs = ElevatorPersonInfo.objects.filter(elevator=elevator_id, worker_type=10)
    #     elevator_worker = []
    #     for e_p in qs:
    #         elevator_worker.append({"person_id": e_p.worker.id, "person_name": e_p.worker.auth_user.real_name})
    #     return elevator_worker

    def get_elevator(self, obj):
        return obj.id

    def get_update_by_people(self, obj):
        if obj.update_by:
            auth_user = AuthUser.objects.get(id=obj.update_by)
            if auth_user:
                return auth_user.username
        return None

    # def get_record(self, obj):
    #     request = self.context.get("request", None)
    #     role = request.user.role
    #     registry = Registry.objects.filter(type_for_reg=obj.__class__.__name__, reg_obj_id=obj.id).last()
    #     record = {
    #         "start_time": u"",
    #         "end_time": u"",
    #         "status": u"",
    #         "msg": u"",
    #         "data": u"",
    #         "reg_info": u"",
    #         "ret_info": u""
    #     }
    #     if registry:
    #         if role == 0 and registry.reg_info:
    #             reg_info = json.loads(registry.reg_info)
    #         else:
    #             reg_info = u""
    #
    #         if role == 0 and registry.ret_info:
    #             ret_info = json.loads(registry.ret_info)
    #         else:
    #             ret_info = u""
    #         record.update({
    #             "start_time": registry.start_time.strftime("%Y-%m-%d %H:%M:%S"),
    #             "end_time": registry.end_time.strftime("%Y-%m-%d %H:%M:%S"),
    #             "rec_status": registry.status,
    #             "msg": registry.msg,
    #             "data": registry.data,
    #             "reg_info": reg_info,
    #             "ret_info": ret_info
    #         })
    #     return record

    def get_telephone(self, obj):
        try:
            return obj.maintain_company.company_webinfo.first().emergency_phone
        except:
            return ""


class ElevatorDetailSerializer(serializers.ModelSerializer):
    update_by_people = serializers.SerializerMethodField()
    elevator = serializers.SerializerMethodField()
    maintain_company_name = serializers.SerializerMethodField()
    property_company_name = serializers.SerializerMethodField()
    telephone = serializers.SerializerMethodField()
    alarm = serializers.SerializerMethodField()

    class Meta:
        model = ElevatorInfo
        fields = ("id", "elevator_name", "elevator_no", "internal_no", "register_code", "property_company",
                  "factory_no", "elevator_model", "installation_company", "maintain_company_name",
                  "maintain_company", "manufacturer_company_name", "manufacturer_company",
                  "property_company_name", "product_company", "elevator_property", 'update_by_people',
                  'update_time', "next_yearly_inspection_date", "phone_num", "next_time",
                  "usage_status", "qr_code", "rated_load", "rated_speed", "stations", "elevator_type", "contract",
                  "elevator", "registry_status", "telephone", "elevator_cycle", "create_time", "alarm", "num",
                  "address", "inspection_people", "inspection_conclusion", "inspection_company")

    def get_maintain_company_name(self, obj):
        maintain_company_name = obj.maintain_company_name
        return maintain_company_name

    def get_property_company_name(self, obj):
        property_company_name = obj.property_company.name
        return property_company_name

    def get_elevator(self, obj):
        return obj.id

    def get_update_by_people(self, obj):
        if obj.update_by:
            auth_user = AuthUser.objects.get(id=obj.update_by)
            if auth_user:
                return auth_user.username
        return None

    def get_telephone(self, obj):
        try:
            return obj.maintain_company.company_webinfo.first().emergency_phone if obj.maintain_company else None
        except:
            return None

    def get_alarm(self, obj):
        now = datetime.datetime.now()
        today = datetime.datetime(year=now.year, month=now.month, day=now.day)
        alarm = AlarmMsg.objects.filter_active(authority_code__elevator_code=obj.register_code, create_time__gte=today)\
            .order_by("-id").first()
        return alarm.get_elevator_alarm() if alarm else []

# class ElevatorPersonSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = ElevatorInfo


# class ElevatorPersonListSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         model = ElevatorInfo
#         fields = ('elevator', 'maintain_worker', 'rescue_worker', 'repair_worker')
#
#         def get_repair_worker(self, obj):
#             pass
#
#         def get_maintain_worker(self, obj):
#             pass
#
#         def get_rescue_worker(self, obj):
#             pass

class ElevatorPersonListSerializer(serializers.ModelSerializer):
    update_by_people = serializers.SerializerMethodField()
    worker = serializers.SerializerMethodField()
    record = serializers.SerializerMethodField()
    property_company_name = serializers.SerializerMethodField()

    class Meta:
        model = ElevatorInfo
        fields = ('id', 'register_code', 'registry_status', 'is_binded', 'update_by_people', 'update_time', 'worker',
                  'register_code', 'record', 'elevator_name', 'property_company_name')

    def get_property_company_name(self, obj):
        property_company = obj.property_company
        return property_company.name if property_company else None

    def get_worker(self, obj):
        elevator_id = obj.id
        maintain_person_qs = ElevatorPersonInfo.objects.filter(elevator=elevator_id, worker_type=10, status=10)
        rescue_person_qs = ElevatorPersonInfo.objects.filter(elevator=elevator_id, worker_type=20, status=10)
        repair_person_qs = ElevatorPersonInfo.objects.filter(elevator=elevator_id, worker_type=30, status=10)
        worker = []
        maintain_person_info = {
            'worker_type': 10,
            'worker_person': []
        }
        rescue_person_info = {
            'worker_type': 20,
            'worker_person': []
        }
        repair_person_info = {
            'worker_type': 30,
            'worker_person': []
        }
        if maintain_person_qs.count() > 0:
            for maintain_person_obj in maintain_person_qs:
                maintain_worker = {}
                maintain_person_id = maintain_person_obj.worker.id
                maintain_person_name = maintain_person_obj.worker.auth_user.real_name
                maintain_worker['work_id'] = maintain_person_id
                maintain_worker['work_name'] = maintain_person_name
                maintain_person_info['worker_person'].append(maintain_worker)
            worker.append(maintain_person_info)
        else:
            worker.append(maintain_person_info)

        if rescue_person_qs.count() > 0:
            for rescue_person_obj in rescue_person_qs:
                rescue_worker = {}
                rescue_person_id = rescue_person_obj.worker.id
                rescue_person_name = rescue_person_obj.worker.auth_user.real_name
                rescue_worker['work_id'] = rescue_person_id
                rescue_worker['work_name'] = rescue_person_name
                rescue_person_info['worker_person'].append(rescue_worker)
            worker.append(rescue_person_info)
        else:
            worker.append(rescue_person_info)

        if repair_person_qs.count() > 0:
            for repair_person_obj in repair_person_qs:
                repair_worker = {}
                repair_person_id = repair_person_obj.worker.id
                repair_person_name = repair_person_obj.worker.auth_user.real_name
                repair_worker['work_id'] = repair_person_id
                repair_worker['work_name'] = repair_person_name
                repair_person_info['worker_person'].append(repair_worker)
            worker.append(repair_person_info)
        else:
            worker.append(repair_person_info)

        return worker

    def get_update_by_people(self, obj):
        if obj.update_by:
            auth_user = AuthUser.objects.get(id=obj.update_by)
            if auth_user:
                return auth_user.username
        return None

    def get_record(self, obj):
        request = self.context.get("request", None)
        role = request.user.role
        registry = Registry.objects.filter(type_for_reg=obj.__class__.__name__, reg_obj_id=obj.id).last()
        record = {
            "start_time": u"",
            "end_time": u"",
            "status": u"",
            "msg": u"",
            "data": u"",
            "reg_info": u"",
            "ret_info": u""
        }
        if registry:
            if role == 0 and registry.reg_info:
                reg_info = json.loads(registry.reg_info)
            else:
                reg_info = u""

            if role == 0 and registry.ret_info:
                ret_info = json.loads(registry.ret_info)
            else:
                ret_info = u""
            record.update({
                "start_time": registry.start_time.strftime("%Y-%m-%d %H:%M:%S"),
                "end_time": registry.end_time.strftime("%Y-%m-%d %H:%M:%S"),
                "rec_status": registry.status,
                "msg": registry.msg,
                "data": registry.data,
                "reg_info": reg_info,
                "ret_info": ret_info
            })
        return record


class ElevatorPersonSerializer(serializers.ModelSerializer):

    class Meta:
        model = ElevatorInfo
        fields = ()


class ElevatorStatisticsListSerializer(serializers.ModelSerializer):
    company_name = serializers.SerializerMethodField()
    month = serializers.SerializerMethodField()

    class Meta:
        model = ElevatorStatistics
        fields = ('month', 'numbers', 'company_name')

    def get_company_name(self, obj):
        return obj.company.name

    def get_month(self, obj):
        return obj.day.isoformat()


class ElevatorFittingsListSerializer(serializers.ModelSerializer):

    class Meta:
        model = ElevatorFittings
        fields = ("id", "elevator", "name", "person", "replace_time", "warranty_time",
                  "atype", "replace_mode", "register_code", "person_name", "number")


class ElevatorFittingsSerializer(serializers.ModelSerializer):

    class Meta:
        model = ElevatorFittings
        fields = ("elevator", "number", "old_number", "name", "person", "replace_time", "warranty_time",
                  "register_files", "atype", "replace_mode", "register_code")


class ElevatorFittingsDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = ElevatorFittings
        fields = ("id", "number", "old_number", "name", "person", "replace_time", "warranty_time",
                  "register_files", "atype", "replace_mode", "register_code", "person_name", "elevator")











